|









| |
I 数据库
003 处理 Select 语句中的单引号 98-8-06
在数据库应用中, 经常要动态生成 Select 语句,典型的情况:
SqlString = "Select * from myBas where Name = '" & Text1 &
"'"
好啦, 问题出现了, 如果在录入的 Text1 中有一个单引号,结果是把
SqlString 发给数据库时, 将出错!
其实要做的防范很简单, 增加一个函数:
FUNCTION CheckString (s) as String
pos = InStr(s, "'")
While pos > 0
s = Mid(s, 1, pos) & "'" & Mid(s, pos + 1)
pos = InStr(pos + 2, s, "'")
Wend
CheckString="'" & s & "'"
END FUNCTION
以后在动态生成 Select 语句, 使用:
SqlString = "Select * from myBas where Name = " &
CheckString(Text1) 
002 非 DSN 的 ODBC 连接 98-8-06
如果使用 DSN 的话, 每台电脑都要设置 ODBC 连接, 可能还要安装
ODBC 驱动程序。 一旦修改 DSN , 要重新设置每台电脑。 不过, 用了
DSN-Less 连接, 就不需要在每台电脑设置 ODBC 啦。
其实要做的非常简单, 只要修改在连接串中设置 driver 和 server 就 OK。如:
cnstr = "driver={SQL Server}; server=myserver;" & "database=mydb;
uid=myuid; pwd=mypwd; dsn=;"
Set cn = en.OpenConnection("", False, False, cnstr)
注意: driver 要用 { },如果使用 DAO 控件, 应该在 Connect 头上增加
"ODBC; "。
001 建立和删除一个 DSN
1. 增加声明:
Private Const ODBC_ADD_DSN = 1 ' Add data source
Private Const ODBC_CONFIG_DSN = 2 ' Configure (edit) data source
Private Const ODBC_REMOVE_DSN = 3 ' Remove data source
Private Const vbAPINull As Long = 0& ' NULL Pointer
Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal
hwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal
lpszAttributes As String) As Long
2. 新增加一个 DSN
Dim intRet As Long
Dim strDriver As String
Dim strAttributes As String
'设置数据库类别 这里是 SQL Server
strDriver = "SQL Server"
'null 结尾的参数
'请看相关文档
strAttributes = "SERVER=SomeServer" & Chr$(0)
strAttributes = strAttributes & "DESCRIPTION=Temp DSN" & Chr$(0)
strAttributes = strAttributes & "DSN=DSN_TEMP" & Chr$(0)
strAttributes = strAttributes & "DATABASE=pubs" & Chr$(0)
strAttributes = strAttributes & "UID=sa" & Chr$(0)
strAttributes = strAttributes & "PWD=" & Chr$(0)
'如果要显示对话,可使用 Form1.Hwnd 代替 vbAPINull.
intRet = SQLConfigDataSource(vbAPINull, ODBC_ADD_DSN, strDriver, strAttributes)
If intRet Then
MsgBox "DSN 建立"
Else
MsgBox "失败"
End If
3. 删除一个 DSN
Dim intRet As Long
Dim strDriver As String
Dim strAttributes As String
strDriver = "SQL Server"
strAttributes = "DSN=DSN_TEMP" & Chr$(0)
intRet = SQLConfigDataSource(vbAPINull, ODBC_REMOVE_DSN, strDriver, strAttributes)
If intRet Then
MsgBox "DSN 删除"
Else
MsgBox "失败"
End If
|